/*
clsquare - closed loop simulation system
Copyright (c) 2004, 2008 Neuroinformatics Group, Prof. Dr. Martin Riedmiller,
University of Osnabrueck

Authors: Martin Riedmiller, Sascha Lange

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
   * Neither the name of the <ORGANIZATION> nor the names of its
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  */

#include <stdio.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <iomanip>
#include "valueparser.h"
#include "str2val.h"
#include "statistics.h"
#include "global.h"

#define OUTPUT(XXX) std::setw(15) << std::setprecision(2)<< std::fixed<< XXX


bool Statistics::open_file()
{ 
  if (statistics_mode == -10)
    return true;

  out = new ofstream(prot_fname);
  if (!out || !*out) {
    EOUT("Can't open file: (" << prot_fname << ")!");
    return false;
  }
       
  if(statistics_mode == 0 && noheader == false){
    //    *out << "# CLSquare statistics file. Standardized Benchmarking format.\n";
    *out << "#";

    *out   
      << OUTPUT("Episode")
      << OUTPUT("Crashed")
      <<OUTPUT("Touched Goal")
      <<OUTPUT("End In Goal")
      <<OUTPUT("Touched Avoid")
      <<OUTPUT("Duration")
      <<OUTPUT("Out Of Goal")    
      <<OUTPUT("Perm. in Goal")
      <<OUTPUT("Average Reward")     
      <<OUTPUT("Avg. FinalReward")     
      <<OUTPUT("Total Cycles")
      <<OUTPUT("Total Runs");
    *out << endl;
  }

 if(statistics_mode == -1 && noheader == false){
   //    *out << "# CLSquare statistics file. Default format.\n";
   *out << "#";   
   *out   
     << OUTPUT("Average Reward")    
     << OUTPUT("Total Cycles");
    *out << endl;
 }
  
  return(true);
}

void Statistics::init_curr_perf(){
  curr_perf.num_cycles = 0;
  curr_perf.touched_goal = false;
  curr_perf.touched_avoid = false;
  curr_perf.touched_out_of_working = false;
  curr_perf.cycles_out_of_goal = false;
  curr_perf.ended_in_goal = false;
  curr_perf.crashed = false; 
  curr_perf.cycles_out_of_goal = 0;
  curr_perf.cycles_until_crashed = 0;
  curr_perf.cycles_until_reached_goal = 0;
  curr_perf.cycles_until_permanent_goal = 0; 
  curr_perf.reward = 0;
  curr_perf.final_reward = 0;
}

void Statistics::init_acc_perf(){
  acc_perf.touched_goal = 0;
  acc_perf.touched_avoid = 0;
  acc_perf.average_cycles_out_of_goal = 0;
  acc_perf.ended_in_goal= 0;
  acc_perf.crashed = 0;  
  acc_perf.average_cycles_out_of_goal= 0;
  acc_perf.average_cycles_until_crashed = 0;
  acc_perf.average_cycles_until_reached_goal = 0;
  acc_perf.average_cycles_until_permanent_goal = 0;
  acc_perf.average_reward = 0;
  acc_perf.average_final_reward = 0;
  acc_perf.cycles_total = 0;
  acc_perf.num_episodes = 0;
}

void Statistics::update_curr_perf(const double* state, const double* observation, const double* action, const double reward){  
  curr_perf.num_cycles++;  

  /*
  cout<<"update currperf.: observation: ";
  for(int i=0;i<type_of_definitions == OBSERVATION_BASED ? observationdim : state_dim;i++){
    cout<<(type_of_definitions == OBSERVATION_BASED ? observation[i] : state[i])<<" ";
  }
  cout<<" num cycles: "<<curr_perf.num_cycles<<endl;
  */
  
  if (curr_perf.touched_goal == false)
    curr_perf.cycles_until_reached_goal++; 
 
  // check status of state:
  if(goal_area.isWithinSet(type_of_definitions == OBSERVATION_BASED ? observation : state, 
                           type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim) && 
     working_area.isWithinSet(type_of_definitions == OBSERVATION_BASED ? observation : state, 
                              type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim)){
    curr_perf.touched_goal = true;     
    //    cout<<" observation within goal!! "<<endl;
  }
  else{    
    //    cout<<" observation outof goal!! "<<endl;
    curr_perf.cycles_out_of_goal++;  
    curr_perf.cycles_until_permanent_goal = curr_perf.num_cycles;
    if (avoid_area.isWithinSet(type_of_definitions == OBSERVATION_BASED ? observation : state, 
                               type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim))
      curr_perf.touched_avoid = true;
    if (working_area.numSubsets() >0 && ! 
        working_area.isWithinSet(type_of_definitions == OBSERVATION_BASED ? observation : state, 
                                 type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim)){
      curr_perf.touched_out_of_working = true;    
      //      cout<<" observation outof working area!! "<<endl;
    }
  }
  
  curr_perf.reward += reward;

  if(curr_perf.touched_avoid || curr_perf.touched_out_of_working) 
    curr_perf.crashed = true; 
  
  if(curr_perf.crashed == false)
    curr_perf.cycles_until_crashed++;    

  /*
  cout<<" curr_perf.touched_avoid: "<<curr_perf.touched_avoid
      <<" out of work: "<<curr_perf.touched_out_of_working <<endl;
  */

}

void Statistics::finish_episode(const double* state, const double* observation, const double final_reward, const bool is_terminal_state){ 
  /*
  cout<<"Finish episode: observation: ";
  for(int i=0;i< type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim;i++){
    cout<< (type_of_definitions == OBSERVATION_BASED ? observation[i] : state[i]) <<" ";
  }
  cout<<" terminal reward: "<<final_reward<<" is terminal state: "<<is_terminal_state;
  */

  if(goal_area.isWithinSet(type_of_definitions == OBSERVATION_BASED ? observation : state, 
                           type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim) && 
     working_area.isWithinSet(type_of_definitions == OBSERVATION_BASED ? observation : state, 
                              type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim)) {
    curr_perf.touched_goal = true;
    curr_perf.ended_in_goal = true;
  }
 
  if(curr_perf.crashed == false)
    curr_perf.cycles_until_crashed = max_cycles_per_episode;
  else {
    curr_perf.cycles_until_permanent_goal = max_cycles_per_episode;
    curr_perf.cycles_out_of_goal += max_cycles_per_episode - curr_perf.num_cycles;
  } 

  if (is_terminal_state)
    curr_perf.reward += final_reward;
  curr_perf.final_reward = final_reward;
}

void Statistics::update_acc_perf(){
  acc_perf.cycles_total += curr_perf.num_cycles;
  acc_perf.num_episodes++; 
  if(curr_perf.touched_goal) 
     acc_perf.touched_goal++; 
  if(curr_perf.touched_avoid) 
    acc_perf.touched_avoid++;
  if(curr_perf.touched_out_of_working) 
    acc_perf.touched_out_of_working++;
  if(curr_perf.ended_in_goal) 
    acc_perf.ended_in_goal++;
  if(curr_perf.crashed) 
    acc_perf.crashed++;
    
  // recurrent computation of average value: xquer_n = (1-alpha) * xquer_n-1 + alpha * x_n
  double alpha = 1.0/ (double)(acc_perf.num_episodes);
  acc_perf.average_cycles_out_of_goal = (1-alpha) * acc_perf.average_cycles_out_of_goal + 
    alpha * curr_perf.cycles_out_of_goal;
  acc_perf.average_cycles_until_crashed = (1-alpha) * acc_perf.average_cycles_until_crashed 
    + alpha * curr_perf.cycles_until_crashed;  
  acc_perf.average_cycles_until_reached_goal = (1-alpha) * acc_perf.average_cycles_until_reached_goal
    + alpha * curr_perf.cycles_until_reached_goal;
  acc_perf.average_cycles_until_permanent_goal = (1-alpha)*acc_perf.average_cycles_until_permanent_goal
    + alpha * curr_perf.cycles_until_permanent_goal;  
  acc_perf.average_reward = (1-alpha)*acc_perf.average_reward
    + alpha * curr_perf.reward;
  acc_perf.average_final_reward = (1-alpha)*acc_perf.average_final_reward
    + alpha * curr_perf.final_reward;
}

void Statistics::write2file_mode0(const long episode){
 double N;
  N= (double) acc_perf.num_episodes;
  if(N==0) // already written
    return;  
  
  *out << " ";  // this compensates the '#' sign in comment lines
  *out 
    <<OUTPUT(episode_ctr_internal)
    <<OUTPUT(acc_perf.crashed / N * 100.)
    <<OUTPUT(acc_perf.touched_goal / N *100.)
    <<OUTPUT(acc_perf.ended_in_goal / N * 100.)
    <<OUTPUT(acc_perf.touched_avoid / N * 100.)
    <<OUTPUT(acc_perf.average_cycles_until_crashed)
    <<OUTPUT(acc_perf.average_cycles_out_of_goal)
    <<OUTPUT(acc_perf.average_cycles_until_permanent_goal)
    <<OUTPUT(acc_perf.average_reward)
    <<OUTPUT(acc_perf.average_final_reward)
    <<OUTPUT(acc_perf.cycles_total)   
    <<OUTPUT(acc_perf.num_episodes)  
    <<endl;
}

void Statistics::write2file_mode1(const long episode){
 double N;
  N= (double) acc_perf.num_episodes;
  if(N==0) // already written
    return;  

	*out << " ";  // this compensates the '#' sign in comment lines
	*out 
	  <<OUTPUT(episode_ctr_internal)
	  <<OUTPUT(acc_perf.ended_in_goal / N * 100.)
	  <<OUTPUT(acc_perf.crashed / N * 100.)
	  <<OUTPUT(acc_perf.average_cycles_out_of_goal)
	  <<OUTPUT(acc_perf.average_cycles_until_crashed)
	  <<OUTPUT(acc_perf.touched_goal / N * 100.)
	  <<OUTPUT(acc_perf.touched_avoid / N * 100)
	  <<OUTPUT(acc_perf.touched_out_of_working / N * 100.)
	  <<OUTPUT(acc_perf.average_reward)
	  <<OUTPUT(acc_perf.average_final_reward)
	  <<OUTPUT(acc_perf.num_episodes)
	  <<endl;	    	       
}

void Statistics::write2file_mode_default(const long episode) {
  double N;
  N= (double) acc_perf.num_episodes;
  if(N==0) // already written
    return;  

	*out << " ";  // this compensates the '#' sign in comment lines
	*out     
	  <<OUTPUT(acc_perf.average_reward)
	  <<OUTPUT(acc_perf.cycles_total)
	  <<endl;	    	       
} 

void Statistics::write2file(const long episode){   
  switch(statistics_mode){
  case 0:
    write2file_mode0(episode);
    break;
  case 1:
    write2file_mode1(episode);
    break;    
  case -1:
    write2file_mode_default(episode);
    break;
  default:
    break;
  }
  init_acc_perf();
}

/*****************************************************************
 * Statistics
 *****************************************************************/

bool Statistics::notify(const double* state, const double* observation, const double* action, const double reward, const long cycle, 
			const long episode, const double total_time, const double episode_time, const long total_num_of_cycles){
 
  update_curr_perf(state, observation, action, reward);
  
  return true;
}

void Statistics::notify_episode_starts(const double* state, const double* observation, const long episode_ctr){
  init_curr_perf();
  episode_ctr_internal ++;
}

void Statistics::notify_episode_stops(const double* final_state, const double* final_observation, const double final_reward, 
				       const bool is_terminal_state, const long episode_ctr){
  finish_episode(final_state, final_observation, final_reward, is_terminal_state);
  update_acc_perf();
  if(average_over_n_episodes >0 && (episode_ctr % average_over_n_episodes) == 0) 
    write2file(episode_ctr);
}

bool Statistics::deinit(){ 
  if(average_over_n_episodes <=0)
    write2file(acc_perf.num_episodes);
  if (out!=0) {
    *out<< std::flush;
    delete out;
  }
  
  return true;
}

bool Statistics::init(int state_dim, int _observation_dim, int _action_dim, double _delta_t, long _max_cycles_per_episode, const char *fname){
  //values
  max_cycles_per_episode  = _max_cycles_per_episode;
  observation_dim         = _observation_dim;
  this->state_dim         = state_dim;
  action_dim              = _action_dim;
  delta_t                 = _delta_t;
  episode_ctr_internal    = 0;
   
  //defaults
  out                  = 0;
  noheader             = false;
  sprintf(prot_fname,"%s","default.stat"); 
  average_over_n_episodes = 1;
  statistics_mode      = -1; // default statistics
  type_of_definitions  = OBSERVATION_BASED;
    
  read_options(fname);
  if(open_file()==false)
    return false; 
  init_acc_perf();
  init_curr_perf();
  return true;
}

bool Statistics::read_options(const char * fname) 
{
  char paramstr[MAX_STR_LEN];
  bool goal_asin_control = false;
  bool work_asin_control = false;
  bool avoid_asin_control = false;

  if(fname == 0)
    return true;

  ValueParser vp(fname,"Statistics");
  if (vp.get("space_of_definitions",paramstr,MAX_STR_LEN)>0) {
    if (strcmp(paramstr,"state")==0) 
      type_of_definitions = STATE_BASED;
    else if (strcmp(paramstr,"observation")==0)
      type_of_definitions = OBSERVATION_BASED;
    else {
      cerr << "did not understand value specified for space_of_definitions in statistics section" << endl;
      return false;
    }
  }
  if(vp.get("goal_area",paramstr,MAX_STR_LEN)>=0){
    if(strcmp(paramstr,"as_in_control")==0)
      goal_asin_control = true;
    else
      goal_area.parseStr(paramstr, type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim);
  }
  if(vp.get("avoid_area",paramstr,MAX_STR_LEN)>=0){
    if(strcmp(paramstr,"as_in_control")==0)
      avoid_asin_control = true;
    else
      avoid_area.parseStr(paramstr, type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim);
  }
  if(vp.get("working_area",paramstr,MAX_STR_LEN)>=0){
    if(strcmp(paramstr,"as_in_control")==0)
      work_asin_control = true;
    else
      working_area.parseStr(paramstr, type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim);
  }
  vp.get("average_over_n_episodes", average_over_n_episodes); 
  if(vp.get("statistics_mode",paramstr,MAX_STR_LEN)>=0){
    if(strcmp(paramstr,"standardized")== 0)
      statistics_mode = 0; 
    else if(strcmp(paramstr,"raw")== 0)
      statistics_mode = 1;    
    else if (strcmp(paramstr,"no_statistics")==0)
      statistics_mode = -10;
    else 
      statistics_mode = -1; // default: (only reward)
  }
  vp.get("noheader", noheader); 
  
  vp.get("statistics_file",prot_fname,MAX_STR_LEN);
  
  ValueParser vp1(fname,"Controller");
  if(goal_asin_control==true){
    if(vp1.get("goal_area",paramstr,MAX_STR_LEN)>=0)
      goal_area.parseStr(paramstr,  type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim);
  }
  if(work_asin_control==true){
    if(vp1.get("working_area",paramstr,MAX_STR_LEN)>=0)
      working_area.parseStr(paramstr,  type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim);
  }
  if(avoid_asin_control==true){
    if(vp1.get("avoid_area",paramstr,MAX_STR_LEN)>=0)
      avoid_area.parseStr(paramstr,  type_of_definitions == OBSERVATION_BASED ? observation_dim : state_dim);
  }
 
  return true;
}
